<script setup lang="ts" name="Sku">
import MyQTable from '@/components/MyQTable.vue';
import { ref, onBeforeMount } from 'vue';
import {
  reqGetSkuList,
  reqToggleSkuSale,
  reqDeleteSku,
  reqGetSkuDetail
} from '@/api/product/sku.ts';
import type { SkuInfo } from '@/api/product/type.ts';
import type { QTableColumn } from 'quasar';
import { useQuasar } from 'quasar';
import { useRemoveItem } from '@/hooks/useRemoveItem.ts';

const { notify } = useQuasar();
//
const columns: QTableColumn[] = [
  {
    name: 'index',
    label: '序号',
    field: '',
    align: 'center',
    style: 'min-width: 80px'
  },
  {
    name: 'skuName',
    label: '名称',
    field: 'skuName',
    align: 'left',
    style: 'min-width: 140px'
  },
  {
    name: 'skuDesc',
    label: '描述',
    field: 'skuDesc',
    align: 'left',
    style: 'min-width: 200px'
  },
  {
    name: 'skuImg',
    label: '图片',
    field: '',
    align: 'left',
    style: 'min-width: 100px'
  },
  {
    name: 'weight',
    label: '重量（g）',
    field: 'weight',
    align: 'left',
    style: 'min-width: 100px'
  },
  {
    name: 'price',
    label: '价格（元）',
    field: 'price',
    align: 'left',
    style: 'min-width: 100px	'
  },
  {
    name: 'control',
    label: '操作',
    field: 'id',
    align: 'center'
  }
];
// 分页选项
// 响应式丢失 要用ref 应该是v-model内部有直接赋值操作
const pagination = ref({
  page: 1, // 当前页数
  rowsPerPage: 10, // 每页数据个数
  rowsNumber: 0, // 总数
  sortBy: '',
  descending: false
});

const loading = ref<boolean>(false);
// skuList
const skuList = ref<SkuInfo[]>([]);
async function getSkuList() {
  loading.value = true;
  try {
    const result = await reqGetSkuList(
      pagination.value.page,
      pagination.value.rowsPerPage
    );
    if (result.code === 200) {
      skuList.value = result.data.records;
      pagination.value.rowsNumber = result.data.total;
    } else {
      throw new Error('获取SKU列表失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  } finally {
    loading.value = false;
  }
}
// 分页器数据
function getTableData(page: number, rowsPerPage: number) {
  pagination.value.page = page;
  pagination.value.rowsPerPage = rowsPerPage;
  getSkuList();
}

// 上下架商品
const isDisabled = ref<boolean>(false);
async function toggleSale(id: number, isSale: number) {
  const onSale = isSale === 0 ? true : false;
  isDisabled.value = true;
  try {
    const result = await reqToggleSkuSale(id, onSale);
    if (result.code === 200) {
      notify({
        type: 'positive',
        message: `商品${onSale ? '上架' : '下架'}成功`,
        position: 'top'
      });
      getSkuList();
    } else {
      throw new Error('操作失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  } finally {
    isDisabled.value = false;
  }
}
// 删除商品
function deleteSku(id: number) {
  useRemoveItem(reqDeleteSku, id, '确认删除该SKU？', getSkuList);
}
// Sku详情
const skuDetailDrawer = ref<boolean>(false);
const skuDetail = ref<SkuInfo>();
async function showSkuDetail(id: number) {
  try {
    const result = await reqGetSkuDetail(id);
    if (result.code === 200) {
      skuDetail.value = result.data;
      skuDetailDrawer.value = true;
      imgSlide.value = 0;
    } else {
      throw new Error('获取SKU详情失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
// 图片轮播
const imgSlide = ref<number>(0);
onBeforeMount(() => {
  getSkuList();
});
</script>

<template>
  <q-card>
    <q-card-section>
      <my-q-table
        :data="skuList"
        :columns="columns"
        v-model:pagination="pagination"
        use-pagination
        @get-table-data="getTableData"
        :rows-per-page-options="[5, 7, 10]"
        :loading="loading"
        class="table-sticky"
      >
        <template #body-cell-control="{ row }">
          <q-td class="bg-light-blue-1">
            <div
              class="flex items-center flex-nowrap q-gutter-xs"
              style="width: 240px"
            >
              <authority permission="btn.Sku.updown" #="{ hasPermission }">
                <hint-button
                  :title="row.isSale === 0 ? '上架商品' : '下架商品'"
                  color="positive"
                  size="xs"
                  :icon="row.isSale === 0 ? 'arrow_upward' : 'arrow_downward'"
                  @click="toggleSale(row.id, row.isSale)"
                  :disabled="isDisabled || !hasPermission"
                ></hint-button>
              </authority>
              <authority permission="btn.Sku.update" #="{ hasPermission }">
                <hint-button
                  title="编辑商品"
                  color="secondary"
                  size="xs"
                  icon="edit"
                  @click="
                    notify({
                      type: 'info',
                      message: '模块开发中',
                      position: 'top'
                    })
                  "
                  :disabled="!hasPermission"
                ></hint-button>
              </authority>
              <authority permission="btn.Sku.detail" #="{ hasPermission }">
                <hint-button
                  title="商品详情"
                  color="info"
                  size="xs"
                  icon="info"
                  @click="showSkuDetail(row.id)"
                  :disabled="!hasPermission"
                ></hint-button>
              </authority>
              <authority permission="btn.Sku.remove" #="{ hasPermission }">
                <hint-button
                  title="删除商品"
                  color="negative"
                  size="xs"
                  icon="delete"
                  @click="deleteSku(row.id)"
                  :disabled="!hasPermission"
                ></hint-button>
              </authority>
            </div>
          </q-td>
        </template>
        <template #body-cell-skuImg="{ row }">
          <q-td>
            <q-img
              style="width: 100px"
              class="q-mr-md"
              :src="row.skuDefaultImg"
            ></q-img>
          </q-td>
        </template>
        <template #body-cell-skuDesc="{ row }">
          <q-td>
            <q-item-label style="min-width: 200px" :lines="5">
              {{ row.skuDesc }}
            </q-item-label>
          </q-td>
        </template>
      </my-q-table>
    </q-card-section>
    <q-drawer
      v-model="skuDetailDrawer"
      side="right"
      overlay
      no-swipe-open
      no-swipe-close
      :width="400"
    >
      <q-scroll-area class="fit">
        <q-list>
          <q-item>
            <q-item-label header class="text-h6">商品详情</q-item-label>
          </q-item>
          <q-item>
            <q-item-section side top>商品名称</q-item-section>
            <q-item-section>{{ skuDetail?.skuName }}</q-item-section>
          </q-item>
          <q-item>
            <q-item-section side top>商品描述</q-item-section>
            <q-item-section>{{ skuDetail?.skuDesc }}</q-item-section>
          </q-item>
          <q-item>
            <q-item-section side top>价格</q-item-section>
            <q-item-section>{{ skuDetail?.price }}元</q-item-section>
          </q-item>
          <q-item>
            <q-item-section side top>平台属性</q-item-section>
            <q-item-section>
              <div class="flex">
                <q-chip
                  v-for="attr in skuDetail?.skuAttrValueList"
                  :key="attr.id"
                  color="primary"
                  text-color="white"
                >
                  {{ attr.valueName }}
                </q-chip>
              </div>
            </q-item-section>
          </q-item>
          <q-item>
            <q-item-section side top>销售属性</q-item-section>
            <q-item-section>
              <template class="flex">
                <q-chip
                  v-for="attr in skuDetail?.skuSaleAttrValueList"
                  :key="attr.id"
                  color="primary"
                  text-color="white"
                >
                  {{ attr.saleAttrValueName }}
                </q-chip>
              </template>
            </q-item-section>
          </q-item>
          <q-item>
            <q-item-section side top>商品图片</q-item-section>
            <q-item-section>
              <q-carousel
                animated
                v-model="imgSlide"
                arrows
                infinite
                autoplay
                thumbnails
                height="300px"
              >
                <q-carousel-slide
                  v-for="(img, i) in skuDetail?.skuImageList"
                  :key="img.id"
                  :name="i"
                  :img-src="img.imgUrl"
                />
              </q-carousel>
            </q-item-section>
          </q-item>
        </q-list>
      </q-scroll-area>
    </q-drawer>
  </q-card>
</template>

<style lang="scss">
/* 固定最后一列 */
.table-sticky {
  max-width: 100%;
  th:last-child,
  td:last-child {
    position: sticky;
    right: 0;
    background-color: #fff;
  }
}
</style>
